<template>
  <view class="page">
    <u-form
      :model="pageForm"
      ref="formRef"
      label-position="top"
      :border-bottom="false"
      :label-style="labelStyle"
      :placeholder-style="placeholderStyle"
    >
      <u-form-item label="所属品牌" prop="brandId" v-if="fromType != 'form'">
        <u-input
          v-model="brandIdDisplayValue"
          type="select"
          @click="showBrandIdSelect = true"
          :select-open="showBrandIdSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择所属品牌"
        />
        <u-select
          v-model="showBrandIdSelect"
          mode="single-column"
          :list="brandIdOptions"
          label-name="label"
          value-name="value"
          @confirm="brandIdSelect"
          :defaultValue="[currentBrandIdIndex]"
        >
        </u-select>
      </u-form-item>

      <u-form-item label="所属店铺" prop="shopId" v-if="fromType != 'form'">
        <u-input
          v-model="shopIdDisplayValue"
          type="select"
          @click="showShopIdSelect = true"
          :select-open="showShopIdSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择所属店铺"
        />
        <u-select
          v-model="showShopIdSelect"
          mode="single-column"
          :list="shopIdOptions"
          label-name="label"
          value-name="value"
          @confirm="shopIdSelect"
          :defaultValue="[currentShopIdIndex]"
        >
        </u-select>
      </u-form-item>

      <u-form-item label="商品名称" prop="goodsName"
        ><u-input v-model="pageForm.goodsName" border :border-color="borderColor" placeholder="请输入名称"
      /></u-form-item>
      <u-form-item label="商品类型" prop="goodsType">
        <u-input
          v-model="goodsTypeDisplayValue"
          type="select"
          @click="showGoodsTypeSelect = true"
          :select-open="showGoodsTypeSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择商品类型"
        />
        <u-select
          v-model="showGoodsTypeSelect"
          mode="single-column"
          :list="goodsTypeOptions"
          label-name="label"
          value-name="value"
          @confirm="goodsTypeSelect"
          :defaultValue="[currentGoodsTypeIndex]"
        >
        </u-select>
      </u-form-item>

      <u-form-item label="商品库存" prop="stock"
        ><u-input v-model="pageForm.stock" border :border-color="borderColor" placeholder="请输入商品库存"
      /></u-form-item>

      <u-form-item label="有效期类型" prop="validTimeType">
        <u-radio-group @change="radioGroupChange">
          <u-radio v-for="(item, index) in validTimeTypeOptions" :key="index" :name="item.name">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>

      <u-form-item label="领取后有效天数" prop="receiveValidDay"
        ><u-input v-model="pageForm.receiveValidDay" border :border-color="borderColor" placeholder="请输入天数" />
      </u-form-item>

      <u-form-item label="适用范围" prop="useScope">
        <u-input
          v-model="useScopeDisplayValue"
          type="select"
          @click="showUseScopeSelect = true"
          :select-open="showUseScopeSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择适用范围"
        />
        <u-select
          v-model="showUseScopeSelect"
          mode="single-column"
          :list="useScopeOptions"
          label-name="label"
          value-name="value"
          @confirm="useScopeSelect"
          :defaultValue="[currentUseScopeIndex]"
        >
        </u-select>
      </u-form-item>

      <u-form-item label="限制使用次数" prop="limitUseCount"
        ><u-input v-model="pageForm.limitUseCount" border :border-color="borderColor" placeholder="请输入次数" />
      </u-form-item>

      <u-form-item label="使用门槛值" prop="useThreshold"
        ><u-input v-model="pageForm.useThreshold" border :border-color="borderColor" placeholder="请输入金额(分)" />
      </u-form-item>

      <u-form-item label="面值" prop="parPrice"
        ><u-input v-model="pageForm.parPrice" border :border-color="borderColor" placeholder="请输入金额(分)" />
      </u-form-item>

      <u-form-item label="市场价" prop="marketPrice"
        ><u-input v-model="pageForm.marketPrice" border :border-color="borderColor" placeholder="请输入金额(分)" />
      </u-form-item>

      <u-form-item label="售价" prop="salePrice"
        ><u-input v-model="pageForm.salePrice" border :border-color="borderColor" placeholder="请输入金额(分)" />
      </u-form-item>

      <u-form-item label="商品详情" prop="goodsDetail"
        ><u-input v-model="pageForm.goodsDetail" border :border-color="borderColor" placeholder="请输入商品详情" />
      </u-form-item>

      <u-form-item label="使用流程" prop="useProcess"
        ><u-input v-model="pageForm.useProcess" border :border-color="borderColor" placeholder="请输入使用流程" />
      </u-form-item>

      <u-form-item label="商品图片(16：9)">
        <u-upload
          ref="uploadRef"
          :auto-upload="false"
          max-count="3"
          :action="UPLOAD_URL"
          :file-list="fileList"
          :customBtn="true"
          width="145rpx"
          height="145rpx"
          :header="uploadHeader"
          @on-uploaded="onUploaded"
        >
          <template v-slot:addBtn>
            <image class="upload_hover_bg" src="/static/upload_hover_bg.png" mode="aspectFill"></image>
          </template>
        </u-upload>
      </u-form-item>
    </u-form>

    <view class="submit" @click="submit">{{ fromType == 'form' ? '确定' : '提交审核' }}</view>
    <view class="safe_area" :style="{ height: '80rpx' }"></view>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onReady, onShow, onLoad } from '@dcloudio/uni-app';
  import { UPLOAD_URL } from '../../config/config';
  import { useFormStore } from '../../store/form';
  import { useUserStore } from '../../store/user';
  import { queryAllBrand, queryAllShop, addGoods } from '../../apis/pages';

  const userStore = useUserStore();
  const formStore = useFormStore();

  const fromType = ref('home');
  const formRef = ref('');

  const borderColor = '#747474';

  const customStyle = {
    width: 'calc(100vw - 200rpx)',
  };

  const pageFormRules = {
    goodsType: [
      {
        required: true,
        message: '请选择商品类型',
        trigger: ['change'],
      },
    ],
  };

  const pageForm = reactive({
    brandId: '', // 品牌id
    shopId: '', // 商家id
    goodsName: '', // 商品名称
    goodsType: '', // 商品类型
    stock: '', // 商品库存
    validTimeType: '', // 有效时间类型
    receiveValidDay: '', // 领取后有效天数
    useScope: '', // 适用范围
    limitUseCount: '', //  限制使用次数
    useThreshold: '', // 使用门槛值
    parPrice: '', // 面值
    marketPrice: '', // 市场价
    salePrice: '', // 售价
    goodsDetail: '', // 商品详情
    useProcess: '', // 使用流程
  });

  const uploadForm = reactive({
    goodsImage: '', //logo图
  });

  const validTimeTypeOptions = ref([
    {
      name: '长期有效',
      value: '1',
    },
    {
      name: '自定义期限',
      value: '2',
    },
    {
      name: '当日有效',
      value: '3',
    },
  ]);

  // 上传相关
  const uploadRef = ref();
  const uploadHeader = {
    authorization: 'Bearer ' + userStore.token,
  };

  // 三个上传完成标志
  const uploadStatus = reactive({
    goodsImageUploaded: false,
  });

  const isSubmit = ref(false);

  // 图片1 是否上传了
  const fileList = ref([]);

  // form 样式相关
  const labelStyle = {
    'font-weight': 600,
    'font-size': '30rpx',
    color: '#1E2737',
    // width: '100%',
  };

  const placeholderStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  const verifyLabelStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  // 归属select
  const showBrandIdSelect = ref(false);
  const brandIdDisplayValue = ref('');
  const currentBrandIdIndex = ref(0);
  const brandIdOptions = ref([]);

  const showShopIdSelect = ref(false);
  const shopIdDisplayValue = ref('');
  const currentShopIdIndex = ref(0);
  const shopIdOptions = ref([]);

  // 商品类型
  const showGoodsTypeSelect = ref(false);
  const goodsTypeDisplayValue = ref('');
  const currentGoodsTypeIndex = ref(0);
  const goodsTypeOptions = [
    {
      label: '自制券',
      value: '1',
    },
    {
      label: '线上券',
      value: '2',
    },
    {
      label: '第三方接口券',
      value: '3',
    },
    {
      label: '实物商品',
      value: '4',
    },
  ];

  // 适用范围
  const showUseScopeSelect = ref(false);
  const currentUseScopeIndex = ref(0);
  const useScopeDisplayValue = ref('');
  const useScopeOptions = [
    {
      label: '仅限本店使用',
      value: '1',
    },
    {
      label: '全品牌通用',
      value: '2',
    },
  ];

  onReady(() => {
    formRef.value.setRules(pageFormRules);
  });

  onLoad((options) => {
    console.log(options, 'options');
    // 从上级表单创建
    fromType.value = options.from;
    getBrandOptions();
    // getShopOptions();
  });

  function getBrandOptions() {
    queryAllBrand({
      merchantId: uni.getStorageSync('merchantId'),
    }).then((res) => {
      console.log(res, 'brands res >>>>>>');
      brandIdOptions.value = res.data.map((item) => {
        return {
          label: item.brandName,
          value: item.id,
        };
      });
    });
  }

  function getShopOptions(id) {
    queryAllShop({
      merchantId: uni.getStorageSync('merchantId'),
      brandId: id,
    }).then((res) => {
      console.log(res, 'shop res >>>>>>');

      if (res.data.length) {
        shopIdOptions.value = res.data.map((item) => {
          return {
            label: item.shopName,
            value: item.id,
          };
        });
      } else {
        shopIdOptions.value = [
          {
            label: '无',
            value: '',
          },
        ];
      }
    });
  }

  function brandIdSelect(e) {
    pageForm.brandId = e[0].value;
    showBrandIdSelect.value = false;
    currentBrandIdIndex.value = e[0].index;
    brandIdDisplayValue.value = e[0].label;
    getShopOptions(pageForm.brandId);
  }

  function shopIdSelect(e) {
    pageForm.shopId = e[0].value;
    showShopIdSelect.value = false;
    currentShopIdIndex.value = e[0].index;
    shopIdDisplayValue.value = e[0].label;
  }

  function goodsTypeSelect(e) {
    pageForm.goodsType = e[0].value;
    showGoodsTypeSelect.value = false;
    currentGoodsTypeIndex.value = e[0].index;
    goodsTypeDisplayValue.value = e[0].label;
  }

  function useScopeSelect(e) {
    pageForm.useScope = e[0].value;
    useScopeDisplayValue.value = e[0].label;
    showUseScopeSelect.value = false;
    currentUseScopeIndex.value = e[0].index;
  }

  function radioGroupChange(e) {
    console.log(e, 'eeee >>>>');
    pageForm.validTimeType = validTimeTypeOptions.value.find((item) => item.name === e)['value'];
    console.log(pageForm.validTimeType, 'pageForm');
  }

  // 上传组件本地图片列表变化
  // function handleListChange(n) {
  //   // uploadRef.value.lists 是获取组件内部展示图片列表
  //   if (uploadRef.value.lists.length > 0) {
  //     isImgUploaded.value = true;
  //   } else {
  //     isImgUploaded.value = false;
  //   }
  // }

  function onUploaded(list) {
    console.log(list, 'list');
    // uploadForm.goodsImage = list[0].response.data;
    uploadForm.goodsImage = list
      .map((item) => {
        return item.response.data;
      })
      .join(',');

    uploadStatus.goodsImageUploaded = true;
    checkAllUploaded();
  }

  // 检查是否全部上传完
  function checkAllUploaded() {
    const allUploaded = Object.values(uploadStatus).every((status) => status);

    if (allUploaded) {
      isSubmit.value = false;
      uni.hideLoading();
      uploadStatus.goodsImageUploaded = false;
      mergeForm();
    }
  }

  // 合并表单
  function mergeForm() {
    console.log('所有图片上传成功，可以合并数据了');
    // 更新页面数据到对应商品
    formStore.updateGoodsById({ ...pageForm, ...uploadForm }, fromType.value);
    if (fromType.value == 'form') {
      // * 确定按钮
      console.log('最终提交的数据：', formStore.brandForm);

      uni.navigateBack();
    } else {
      // * 提交审核(首页建商品)
      console.log('最终提交的数据：', formStore.goodsForm);
      addGoods(formStore.goodsForm).then((res) => {
        console.log(res, 'res >>>');
        if (res.code == 200) {
          uni.reLaunch({ url: '/pagesB/register/finish' });
        }
      });
    }
  }

  function submit() {
    formRef.value.validate((valid) => {
      if (valid) {
        if (isSubmit.value) return;
        console.log(pageForm, 'pageForm >>>');
        if (uploadRef.value.lists.length) {
          isSubmit.value = true;
          uni.showLoading({
            title: '提交中...',
            mask: true,
          });
          uploadRef.value.upload();
        } else {
          mergeForm();
        }
      }
    });
  }
</script>

<style scoped lang="scss">
  // /deep/ .u-form-item {
  //   padding-bottom: 0 !important;
  // }

  .page {
    width: 100vw;
    min-height: 100vh;
    padding: 40rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    background-color: #f5f5f5;
  }

  .upload_hover_bg {
    width: 145rpx;
    height: 145rpx;
    vertical-align: middle;
  }

  .content {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    box-sizing: border-box;
    margin-bottom: 30rpx;
  }

  .label_title {
    font-weight: 600;
    font-size: 30rpx;
    color: #1e2737;
    margin-bottom: 30rpx;
  }

  .verify_form {
    padding: 0 20rpx;
  }

  .upload_box {
    margin-bottom: 20rpx;
  }

  .hover_box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: calc(100vw - 80rpx);
    height: calc((100vw - 80rpx) * 0.4414);
    background-color: #e5e5e5;
    border-radius: 20rpx;
    overflow: hidden;

    .img {
      width: 102rpx;
      height: 102rpx;
    }
  }

  .upload_tip {
    font-weight: 500;
    font-size: 26rpx;
    color: #989898;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .create_btn {
    width: 188rpx;
    height: 67rpx;
    border: 2rpx solid #4287f6;
    text-align: center;
    line-height: 67rpx;
    box-sizing: border-box;
    font-weight: 500;
    font-size: 27rpx;
    color: #4287f6;
    border-radius: 40rpx;
    margin-bottom: 32rpx;
  }

  .created_list {
    margin-bottom: 40rpx;

    .item {
      font-weight: 600;
      font-size: 30rpx;
      color: #1e2737;
      border-bottom: 2rpx solid #e5e5e5;
      padding-left: 4rpx;
      padding-bottom: 12rpx;
      margin-bottom: 16rpx;
    }
  }

  .submit {
    width: 537rpx;
    height: 83rpx;
    background: #016bec;
    border-radius: 10rpx;

    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;

    text-align: center;
    line-height: 83rpx;
    margin: 0 auto;
    margin-top: 65rpx;
  }

  .backup_phones {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    .add_btn {
      width: 64rpx;
      min-width: 64rpx;
      height: 64rpx;
      margin-left: 12rpx;
    }
  }
</style>
